package com.linkage.jz.bankruptcy.activity.Project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.TalkDetailAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProTalkDetail;
import com.linkage.jz.bankruptcy.bean.ProTalkReply;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.widget.CommonPopupMenu;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 话题详情
 */
public class ProTalkDetailActivity extends BaseActivity implements OnClickListener {
    public static final String KEY_ID = "talkid";

    private String mProjectId;
    private String mTalkId;
    private CommonPopupMenu popupMenu;
    private ProTalkDetail mTalkDetail;
    private List<ProTalkReply> mReplyList = new ArrayList<>();
    private TalkDetailAdapter mAdapter;
    private RecyclerView mRecyclerView;

    private EditText mEtContent;

    private boolean editDiscussion = false;  //
    private boolean deleteDiscussion = false;
    private boolean deleteReply = true;
    private boolean bannedDiscussion = false;
    private boolean canReply = false;


    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_talk_detail);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("话题详情");

        EventBus.getDefault().register(this);
        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        mTalkId = getIntent().getStringExtra(KEY_ID);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView = findViewById(R.id.rv_talk_detail);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new TalkDetailAdapter(this, mReplyList);
        mRecyclerView.setAdapter(mAdapter);
        mEtContent = findViewById(R.id.et_reply);

        getDetail();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TALK)) {
            finish();
        } else if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TALK_REPLY)) {
            getReplyList();
        }
    }

    @Override
    public void initView() {
    }


    public void getDetail() {
        Network
                .getAPIService()
                .getTalkDetail(getUserToken(), mTalkId, 1, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");


                        try {
                            //编辑
                            editDiscussion = data.getAsJsonObject("auth").get("editDiscussion").getAsBoolean();
                            //删除
                            deleteDiscussion = data.getAsJsonObject("auth").get("deleteDiscussion").getAsBoolean();

                            bannedDiscussion = data.getAsJsonObject("auth").get("banned").getAsBoolean();
//                            deleteReply = data.getAsJsonObject("auth").get("deleteReply").getAsBoolean();
                        canReply = data.getAsJsonObject("auth").get("isBanned").getAsBoolean();
//                            editDiscussion = false;
//                            deleteDiscussion = false;
//                            bannedDiscussion = false;
//                            canReply = false;
                        }catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }

                        mTalkDetail = ProTalkDetail.parse(data.getAsJsonObject("subjectDetail"));

                        mAdapter.setBannedDiscussion(bannedDiscussion);
                        mAdapter.setTalkDetail(mTalkDetail);
                        mAdapter.notifyDataSetChanged();

                        refreshAction();
                        getReplyList();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    private void refreshAction() {
        mAdapter.setBannedDiscussion(bannedDiscussion);
        mAdapter.setDeleteReply(deleteReply);

        List<String> menus = new ArrayList<>();
        if (editDiscussion) {
            menus.add("编辑话题");
            menus.add("成员管理");
        }
        if (deleteDiscussion) {
            menus.add("删除话题");
        }
        if (menus.size() == 0) {
            titlebar_menu.setVisibility(View.GONE);
            return;
        }
        popupMenu = new CommonPopupMenu(this, menus);
        titlebar_menu.setVisibility(View.VISIBLE);
        titlebar_menu.setOnClickListener(v -> {
            popupMenu.showLocation(R.id.titlebar_menu);
            popupMenu.setOnItemClickListener((index, str) -> {
                if (TextUtils.equals(str, "编辑话题")) {
                    //编辑
                    Intent intent = new Intent(ProTalkDetailActivity.this, CreateProTalkActivity.class);
                    intent.putExtra(CreateProTalkActivity.KEY_ACTION, "edit");
                    intent.putExtra(KEY_PROJECTID, mProjectId);
                    intent.putExtra(CreateProTalkActivity.KEY_TALK, mTalkDetail);
                    startActivity(intent);
                } else if (TextUtils.equals(str, "成员管理")) {
                    //编辑
                    Intent intent = new Intent(ProTalkDetailActivity.this,
                            ProTalkManageMemberActivity.class);
                    intent.putExtra(ProTalkManageMemberActivity.KEY_TALKID, mTalkDetail.getId());
                    intent.putExtra(KEY_PROJECTID, mProjectId);
                    startActivity(intent);
                } else {
                    //删除
                    Dialog tipDialog = new AlertDialog
                            .Builder(ProTalkDetailActivity.this)
                            .setTitle("提示")
                            .setMessage("确认删除当前话题吗？")
                            .setPositiveButton(R.string.confirm, (dialog, which) -> deleteTalk()).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).create();
                    tipDialog.setCancelable(false);
                    tipDialog.show();
                }
            });
        });
    }

    private void deleteTalk() {
        Network
                .getAPIService()
                .deleteTalk(getUserToken(), mTalkId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mShapeLoadingDialog.show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TALK);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("话题已删除");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    private void getReplyList() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        Network
                .getAPIService()
                .getTalkReplyList(getUserToken(), mTalkId, 1, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        if (data != null) {
                            JsonArray arr = data.getAsJsonArray("list");
                            List<ProTalkReply> list = ProTalkReply.parse(arr);
                            mReplyList.clear();
                            mReplyList.addAll(list);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                if (!canReply) {
                    ToastUtil.showShort("您没有回复权限");
                    return;
                }

                String content = mEtContent.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.showShort("回复内容不能为空");
                    return;
                }

                Network
                        .getAPIService()
                        .sendTalkReply(mTalkId, content, getUserToken())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseSubscriber<JsonObject>() {
                            @Override
                            public void onNext(JsonObject json) {
                                int code = json.get("code").getAsInt();
                                if (code != 0) {
                                    super.onNext(json);
                                    return;
                                }
                                ToastUtil.showShort("回复成功");
                                mEtContent.setText("");
                                getReplyList();
                            }

                            @Override
                            public void onCompleted() {
                                super.onCompleted();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                            }
                        });

                break;
        }
    }
}
